<script setup>
import { ref, reactive, onMounted } from 'vue'

// 用户状态选项
const userStatusOptions = [
    { value: '1', label: '正常' },
    { value: '0', label: '禁用' }
]

// 用户等级选项
const userLevelOptions = [
    { value: '0', label: '普通会员' },
    { value: '1', label: '银牌会员' },
    { value: '2', label: '金牌会员' },
    { value: '3', label: 'VIP会员' }
]

// 搜索条件
const searchForm = reactive({
    keyword: '',
    status: '',
    dateRange: [],
    userLevel: ''
})

// 表格数据
const tableData = ref([
    {
        id: 1001,
        avatar: 'https://via.placeholder.com/40',
        nickname: '用户18812345678',
        username: '18812345678',
        level: '2',
        gender: '男',
        birthday: '1990-01-15',
        registerTime: '2022-05-10 14:30:24',
        lastLoginTime: '2023-07-12 09:25:36',
        totalConsume: 3560.50,
        orderCount: 15,
        status: '1',
        tags: ['活跃用户', '多次购买']
    },
    {
        id: 1002,
        avatar: 'https://via.placeholder.com/40',
        nickname: '小李子',
        username: '13987654321',
        level: '3',
        gender: '女',
        birthday: '1995-06-18',
        registerTime: '2022-03-22 09:15:38',
        lastLoginTime: '2023-07-10 20:45:12',
        totalConsume: 8920.00,
        orderCount: 26,
        status: '1',
        tags: ['高消费', 'VIP客户']
    },
    {
        id: 1003,
        avatar: 'https://via.placeholder.com/40',
        nickname: '张大大',
        username: '15598765432',
        level: '1',
        gender: '男',
        birthday: '1985-11-25',
        registerTime: '2023-01-15 16:42:19',
        lastLoginTime: '2023-07-11 14:38:52',
        totalConsume: 1290.50,
        orderCount: 5,
        status: '1',
        tags: ['新用户']
    },
    {
        id: 1004,
        avatar: 'https://via.placeholder.com/40',
        nickname: '小王子',
        username: '13656789012',
        level: '0',
        gender: '男',
        birthday: '1992-08-10',
        registerTime: '2023-05-28 11:26:35',
        lastLoginTime: '2023-06-30 19:20:15',
        totalConsume: 356.00,
        orderCount: 2,
        status: '0',
        tags: ['已禁用']
    },
    {
        id: 1005,
        avatar: 'https://via.placeholder.com/40',
        nickname: '蓝莓冰沙',
        username: '18123456789',
        level: '1',
        gender: '女',
        birthday: '1988-03-09',
        registerTime: '2022-12-18 10:52:47',
        lastLoginTime: '2023-07-08 15:12:30',
        totalConsume: 2768.00,
        orderCount: 9,
        status: '1',
        tags: ['活跃用户']
    }
])

// 分页配置
const pagination = reactive({
    total: 100,
    currentPage: 1,
    pageSize: 10
})

// 表格加载状态
const tableLoading = ref(false)

// 搜索方法
const handleSearch = () => {
    tableLoading.value = true
    // 这里应该是实际的API调用
    setTimeout(() => {
        tableLoading.value = false
        // 模拟搜索结果
        console.log('搜索条件:', searchForm)
    }, 500)
}

// 重置搜索条件
const resetSearch = () => {
    Object.keys(searchForm).forEach(key => {
        if (key === 'dateRange') {
            searchForm[key] = []
        } else {
            searchForm[key] = ''
        }
    })
    handleSearch()
}

// 处理分页变化
const handleCurrentChange = (val) => {
    pagination.currentPage = val
    handleSearch()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
    pagination.pageSize = val
    pagination.currentPage = 1
    handleSearch()
}

// 获取用户状态对应的标签类型
const getStatusType = (status) => {
    return status === '1' ? 'success' : 'danger'
}

// 获取用户状态文本
const getStatusText = (status) => {
    return status === '1' ? '正常' : '禁用'
}

// 获取用户等级文本
const getLevelText = (level) => {
    return userLevelOptions.find(item => item.value === level)?.label || '普通会员'
}

// 获取用户等级颜色
const getLevelColor = (level) => {
    switch (level) {
        case '0': return '#909399'
        case '1': return '#67C23A'
        case '2': return '#E6A23C'
        case '3': return '#F56C6C'
        default: return '#909399'
    }
}

// 用户详情对话框
const detailDialogVisible = ref(false)
const currentUser = ref(null)

// 打开用户详情
const openUserDetail = (user) => {
    currentUser.value = user
    detailDialogVisible.value = true
}

// 用户标签编辑对话框
const tagDialogVisible = ref(false)
const currentTags = ref([])
const inputTagValue = ref('')
const inputTagVisible = ref(false)

// 打开标签编辑
const openTagDialog = (user) => {
    currentUser.value = user
    currentTags.value = [...user.tags]
    tagDialogVisible.value = true
}

// 添加标签
const handleInputConfirm = () => {
    const value = inputTagValue.value
    if (value && !currentTags.value.includes(value)) {
        currentTags.value.push(value)
    }
    inputTagVisible.value = false
    inputTagValue.value = ''
}

// 移除标签
const handleTagClose = (tag) => {
    currentTags.value.splice(currentTags.value.indexOf(tag), 1)
}

// 保存标签
const saveUserTags = () => {
    // 这里应该是调用保存标签的API
    if (currentUser.value) {
        currentUser.value.tags = [...currentTags.value]
        ElMessage.success('标签保存成功')
        tagDialogVisible.value = false
    }
}

// 修改用户状态
const changeUserStatus = (user) => {
    const newStatus = user.status === '1' ? '0' : '1'
    const actionText = newStatus === '1' ? '启用' : '禁用'

    ElMessageBox.confirm(`确认要${actionText}该用户吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        // 调用修改状态API
        user.status = newStatus
        ElMessage.success(`用户已${actionText}`)
    }).catch(() => { })
}

onMounted(() => {
    handleSearch()
})
</script>

<template>
    <div class="user-container">
        <!-- 搜索栏 -->
        <el-card class="search-card">
            <el-form :model="searchForm" label-width="80px" :inline="true" size="default" class="responsive-form">
                <el-form-item label="用户搜索">
                    <el-input v-model="searchForm.keyword" placeholder="用户名/昵称/手机号" clearable />
                </el-form-item>
                <el-form-item label="用户状态">
                    <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                        <el-option v-for="item in userStatusOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="用户等级">
                    <el-select v-model="searchForm.userLevel" placeholder="请选择等级" clearable>
                        <el-option v-for="item in userLevelOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="注册时间" class="date-form-item">
                    <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item class="form-buttons">
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 操作栏 -->
        <div class="action-bar">
            <el-button type="primary" icon="Plus">添加用户</el-button>
            <el-button icon="Upload">导入用户</el-button>
            <el-button icon="Download">导出用户</el-button>
            <el-button type="success" icon="Message">群发消息</el-button>
        </div>

        <!-- 表格 -->
        <el-card>
            <div class="table-responsive">
                <el-table v-loading="tableLoading" :data="tableData" style="width: 100%">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="id" label="ID" min-width="80" />
                    <el-table-column label="用户信息" min-width="200">
                        <template #default="scope">
                            <div class="user-info">
                                <el-avatar :size="40" :src="scope.row.avatar" />
                                <div class="user-details">
                                    <div class="nickname">{{ scope.row.nickname }}</div>
                                    <div class="username">{{ scope.row.username }}</div>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="用户等级" min-width="110">
                        <template #default="scope">
                            <el-tag :color="getLevelColor(scope.row.level)" effect="dark">
                                {{ getLevelText(scope.row.level) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="消费情况" min-width="150">
                        <template #default="scope">
                            <div>总消费: ￥{{ scope.row.totalConsume.toFixed(2) }}</div>
                            <div>订单数: {{ scope.row.orderCount }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="注册/登录时间" min-width="200">
                        <template #default="scope">
                            <div>注册: {{ scope.row.registerTime }}</div>
                            <div>最近登录: {{ scope.row.lastLoginTime }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="标签" min-width="200">
                        <template #default="scope">
                            <div class="user-tags">
                                <el-tag v-for="tag in scope.row.tags" :key="tag" size="small" class="tag">
                                    {{ tag }}
                                </el-tag>
                                <el-button type="primary" size="small" circle @click="openTagDialog(scope.row)">
                                    <el-icon>
                                        <Edit />
                                    </el-icon>
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" min-width="80">
                        <template #default="scope">
                            <el-tag :type="getStatusType(scope.row.status)">
                                {{ getStatusText(scope.row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" min-width="220" fixed="right">
                        <template #default="scope">
                            <div class="action-buttons">
                                <el-button type="primary" size="small" @click="openUserDetail(scope.row)">详情</el-button>
                                <el-button :type="scope.row.status === '1' ? 'danger' : 'success'" size="small"
                                    @click="changeUserStatus(scope.row)">
                                    {{ scope.row.status === '1' ? '禁用' : '启用' }}
                                </el-button>
                                <el-dropdown size="small">
                                    <el-button size="small">
                                        更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                                    </el-button>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item>修改资料</el-dropdown-item>
                                            <el-dropdown-item>充值余额</el-dropdown-item>
                                            <el-dropdown-item>积分记录</el-dropdown-item>
                                            <el-dropdown-item>购买记录</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 用户详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="用户详情" width="90%" max-width="700px" destroy-on-close>
            <template v-if="currentUser">
                <div class="user-detail-header">
                    <el-avatar :size="80" :src="currentUser.avatar" />
                    <div class="user-detail-info">
                        <div class="user-detail-name">
                            <h3>{{ currentUser.nickname }}</h3>
                            <el-tag :color="getLevelColor(currentUser.level)" effect="dark" size="small">
                                {{ getLevelText(currentUser.level) }}
                            </el-tag>
                            <el-tag :type="getStatusType(currentUser.status)" size="small">
                                {{ getStatusText(currentUser.status) }}
                            </el-tag>
                        </div>
                        <div class="user-detail-tags">
                            <el-tag v-for="tag in currentUser.tags" :key="tag" size="small" class="tag">
                                {{ tag }}
                            </el-tag>
                        </div>
                    </div>
                </div>

                <el-divider />

                <el-descriptions title="基本信息" :column="2" border>
                    <el-descriptions-item label="用户ID">{{ currentUser.id }}</el-descriptions-item>
                    <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
                    <el-descriptions-item label="性别">{{ currentUser.gender }}</el-descriptions-item>
                    <el-descriptions-item label="生日">{{ currentUser.birthday }}</el-descriptions-item>
                    <el-descriptions-item label="注册时间">{{ currentUser.registerTime }}</el-descriptions-item>
                    <el-descriptions-item label="最近登录">{{ currentUser.lastLoginTime }}</el-descriptions-item>
                </el-descriptions>

                <el-descriptions title="消费信息" :column="2" border class="mt-20">
                    <el-descriptions-item label="总消费金额">￥{{ currentUser.totalConsume.toFixed(2)
                    }}</el-descriptions-item>
                    <el-descriptions-item label="订单总数">{{ currentUser.orderCount }}</el-descriptions-item>
                </el-descriptions>

                <div class="user-detail-actions mt-20">
                    <el-button type="primary">发送消息</el-button>
                    <el-button>查看订单</el-button>
                    <el-button>积分明细</el-button>
                    <el-button>购买记录</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 标签编辑对话框 -->
        <el-dialog v-model="tagDialogVisible" title="编辑用户标签" width="90%" max-width="500px">
            <template v-if="currentUser">
                <div class="edit-tags">
                    <el-tag v-for="tag in currentTags" :key="tag" closable @close="handleTagClose(tag)" class="tag">
                        {{ tag }}
                    </el-tag>
                    <el-input v-if="inputTagVisible" ref="InputRef" v-model="inputTagValue" class="input-new-tag"
                        size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                    <el-button v-else class="button-new-tag" size="small" @click="inputTagVisible = true">
                        + 新标签
                    </el-button>
                </div>

                <div class="common-tags mt-20">
                    <div class="section-title">常用标签</div>
                    <div class="tag-list">
                        <el-tag v-for="tag in ['高消费', '活跃用户', '新用户', '多次购买', 'VIP客户', '流失用户']" :key="tag"
                            @click="!currentTags.includes(tag) && currentTags.push(tag)" class="tag clickable"
                            effect="plain">
                            {{ tag }}
                        </el-tag>
                    </div>
                </div>
            </template>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="tagDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveUserTags">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.user-container {
    padding: 20px;
    width: 100%;
}

.page-title {
    margin-bottom: 20px;
    font-weight: 500;
    color: #303133;
}

.search-card {
    margin-bottom: 20px;
}

.responsive-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.responsive-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
}

.date-form-item {
    min-width: 360px;
}

.action-bar {
    margin-bottom: 20px;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.table-responsive {
    width: 100%;
    overflow-x: auto;
}

.user-info {
    display: flex;
    align-items: center;
}

.user-details {
    margin-left: 10px;
}

.nickname {
    font-weight: 500;
}

.username {
    font-size: 12px;
    color: #909399;
}

.user-tags {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 5px;
}

.action-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.tag {
    margin-right: 5px;
    margin-bottom: 5px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.user-detail-header {
    display: flex;
    margin-bottom: 20px;
    flex-wrap: wrap;
}

.user-detail-info {
    margin-left: 20px;
    flex: 1;
    min-width: 200px;
}

.user-detail-name {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
    flex-wrap: wrap;
}

.user-detail-name h3 {
    margin: 0;
}

.user-detail-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.mt-20 {
    margin-top: 20px;
}

.user-detail-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.edit-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    margin-bottom: 20px;
}

.input-new-tag {
    width: 90px;
    margin-left: 5px;
    vertical-align: bottom;
}

.section-title {
    font-weight: bold;
    margin-bottom: 10px;
}

.tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.clickable {
    cursor: pointer;
}

@media (max-width: 1200px) {
    .user-detail-actions {
        flex-wrap: wrap;
    }

    .action-bar {
        flex-wrap: wrap;
    }
}

@media (max-width: 768px) {
    .user-container {
        padding: 10px;
    }

    .responsive-form .el-form-item {
        flex-basis: 100%;
    }

    .date-form-item {
        min-width: 100%;
    }

    .form-buttons {
        display: flex;
        justify-content: flex-end;
        width: 100%;
    }

    .pagination-container {
        justify-content: center;
    }

    .user-detail-header {
        flex-direction: column;
        align-items: center;
        text-align: center;
    }

    .user-detail-info {
        margin-left: 0;
        margin-top: 15px;
    }

    .user-detail-name {
        justify-content: center;
    }

    .user-detail-tags {
        justify-content: center;
    }

    .user-detail-actions {
        justify-content: center;
    }

    :deep(.el-descriptions__cell) {
        padding: 8px !important;
    }

    :deep(.el-pagination__sizes) {
        display: none !important;
    }
}

@media (max-width: 576px) {
    .action-bar {
        flex-direction: column;
        align-items: stretch;
    }

    .action-buttons {
        flex-direction: column;
    }

    :deep(.el-descriptions__label) {
        width: 80px !important;
    }

    :deep(.el-pagination__jump) {
        display: none !important;
    }

    .user-detail-actions {
        flex-direction: column;
        width: 100%;
    }

    .user-detail-actions .el-button {
        margin-right: 0;
        width: 100%;
    }
}
</style>